package com.rtx.wms.std.qm.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.qimen.api.QimenClient;
import com.qimen.api.QimenRequest;
import com.qimen.api.request.StockoutConfirmRequest;
import com.qimen.api.request.StockoutConfirmRequest.Item;
import com.qimen.api.request.StockoutConfirmRequest.Package;
import com.qimen.api.response.StockoutConfirmResponse;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.log.bean.WmsLogBo;
import com.rtx.wms.std.log.service.impl.StockoutConfirmLog;
import com.rtx.wms.std.so.bean.ApiOrderdetailfinish;
import com.rtx.wms.std.so.bean.ApiOrdersfinish;
import com.rtx.wms.std.so.bean.Pickdetail;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.XmlWriter;

import cn.hutool.core.date.DateUtil;

/**
 * 出库单确认
 */
@SuppressWarnings("all")
@Service
public class StockoutConfirmService extends QimenService{
	
	@Autowired
	StockoutConfirmLog stockoutConfirmLog;

    /**
     * 出库单确认
     * @param apiOrdersfinish
     */
    public void stockoutConfirm(String wmwhseid,ApiOrdersfinish apiOrdersfinish){
        QimenClient client = getQimenClient();
		//利发测试
		if(Arrays.asList("C1689650364732,C1688969618777".split(",")).contains(apiOrdersfinish.getQmcustomerid())) {
			client = getTestQimenClient();
		}
		if(apiOrdersfinish.getQmcustomerid().startsWith("C")) {
			client = getTestQimenClient();
		}
        StockoutConfirmRequest req = new StockoutConfirmRequest();
        req.setCustomerId(apiOrdersfinish.getQmcustomerid());
        StockoutConfirmRequest.DeliveryOrder deliveryOrder = new StockoutConfirmRequest.DeliveryOrder();
        deliveryOrder.setTotalOrderLines(Long.valueOf(apiOrdersfinish.getDetails().size()));
        deliveryOrder.setDeliveryOrderCode(apiOrdersfinish.getExternorderkey());
        deliveryOrder.setDeliveryOrderId(apiOrdersfinish.getOrderkey());
        deliveryOrder.setWarehouseCode(apiOrdersfinish.getWhseid());
        deliveryOrder.setOrderType(apiOrdersfinish.getRtxqmtype());
        if("QT".equals(apiOrdersfinish.getCarriercode())) {
        	deliveryOrder.setLogisticsCode(apiOrdersfinish.getRtxcarriercode());
        }else {
        	deliveryOrder.setLogisticsCode(apiOrdersfinish.getCarriercode());
        }
        deliveryOrder.setLogisticsName(apiOrdersfinish.getCarriername());
        String rtxexpresskey =apiOrdersfinish.getRtxexpresskey();
        if(!StringUtils.hasLength(rtxexpresskey)) {
        	rtxexpresskey = System.currentTimeMillis()+"";
        }
        deliveryOrder.setExpressCode(rtxexpresskey);
//        deliveryOrder.setOrderConfirmTime(DateUtil.format(apiOrdersfinish.getActualshipdate(),"yyyy-MM-dd HH:mm:ss"));
//        deliveryOrder.setOperateTime(DateUtil.format(apiOrdersfinish.getActualshipdate(),"yyyy-MM-dd HH:mm:ss"));
        req.setDeliveryOrder(deliveryOrder);
        List<StockoutConfirmRequest.OrderLine> orderLines = new ArrayList<>();
        for(ApiOrderdetailfinish detail : apiOrdersfinish.getDetails()){
            StockoutConfirmRequest.OrderLine orderLine = new StockoutConfirmRequest.OrderLine();
            orderLine.setOrderLineNo(detail.getExternlineno());
            orderLine.setItemCode(detail.getSku());
            orderLine.setActualQty(detail.getShippedqty().intValue() + "");
            orderLines.add(orderLine);
        }
        req.setOrderLines(orderLines);
        
        //力庚逻辑
        handleStorer2282(req,apiOrdersfinish);
        //
        handle2366(req,apiOrdersfinish);
        
		WmsLogBo logBo = new WmsLogBo();
        
        try {
	        logBo.setOriginalData(apiOrdersfinish);
	        logBo.setApiRequest(req);
	        
			String uuid = UUID.randomUUID().toString();
			XmlWriter writer = new XmlWriter(true, "request", QimenRequest.class);
			String requestStr = writer.write(req);
			logger.info("uuid{}-Stockout-{}-stockout回传数据:{}",uuid,apiOrdersfinish.getExternorderkey(),requestStr);
            StockoutConfirmResponse rsp = client.execute(req);
            logBo.setApiResponse(rsp);
            logger.info("uuid{}-Stockout-{}-stockout响应:{}",uuid,apiOrdersfinish.getExternorderkey(),JSON.toJSONString(rsp));
            if(rsp.isSuccess()){
                apiOrdersfinish.setEdiflag(WmsConstant.SUCCESS_FLAG);
            }else{
            	String msg = Optional.ofNullable(rsp.getMessage()).orElse("");
            	if(msg.contains("订单已出库")) {
            		apiOrdersfinish.setEdiflag(WmsConstant.SUCCESS_FLAG);
            	}else {
            		apiOrdersfinish.setEdiflag(WmsConstant.FAIL_FLAG);
            		apiOrdersfinish.setEdimsg(rsp.getMessage());
            	}
            }
        } catch (ApiException e) {
            logger.error("出库单：{}回传奇门异常",apiOrdersfinish.getOrderkey(),e);
            apiOrdersfinish.setEdiflag(WmsConstant.FAIL_FLAG);
            apiOrdersfinish.setEdimsg(e.getMessage());
            logBo.setMsg(e.getMessage());
        }
        
		try {
			stockoutConfirmLog.recordLog(wmwhseid, logBo);
		} catch (Exception e) {
			logger.error("记录日志异常",e);
		}
    }
    
    /**
     * 力庚货主逻辑
     */
    private void handleStorer2282(StockoutConfirmRequest req,ApiOrdersfinish apiOrdersfinish) {
    	if("2282".equals(apiOrdersfinish.getStorerkey())) {
    		List<Pickdetail> pickdetail = apiOrdersfinish.getPickdetails();
    		
    		List<Package> packages = new ArrayList<StockoutConfirmRequest.Package>();
    		
    		Map<String,List<Pickdetail>> map = pickdetail.stream().collect(Collectors.groupingBy(Pickdetail::getId));
    		
    		for(String id:map.keySet()) {
    			List<Pickdetail>  list = map.get(id);
    			Package packageDTO = new Package();
    			packageDTO.setExpressCode(list.get(0).getId());
    			packageDTO.setPackageCode(list.get(0).getCaseid());
    			packageDTO.setLogisticsCode(apiOrdersfinish.getCarriercode());
    			List<Item> itemList = new ArrayList<StockoutConfirmRequest.Item>();
    			for(Pickdetail detail:list) {
    				Item item = new Item();
    				item.setItemCode(detail.getSku());
    				item.setQuantity(new Double(detail.getQty()).intValue()+"");
    				itemList.add(item);
    			}
    			packageDTO.setItems(itemList);
    			
    			packages.add(packageDTO);
    		}
    		req.setPackages(packages);
    	}
    }
	
    //兆君回传逻辑
	void handle2366(StockoutConfirmRequest req,ApiOrdersfinish apiOrdersfinish){
		if("2366".equals(apiOrdersfinish.getStorerkey())) {
			req.getDeliveryOrder().setOwnerCode(apiOrdersfinish.getDefault01());
		}
}
}
